/*
 * File: Photos
 * Project: App
 * Created Date: Thursday 2018/03/08 15:06:17
 * Author: zhengjiang
 * -----
 * Last Modified:
 * Modified By:
 * -----
 * Description:
 *
 */

import React, { Component } from 'react';
import { Image, StatusBar, StyleSheet, TouchableOpacity, View, Text, FlatList, Dimensions } from 'react-native';
import RNCameraRoll from 'react-native-cameraroll';
import ImageResizer from 'react-native-image-resizer';

const { height, width } = Dimensions.get('window');

let upurl = 'http://192.168.31.28:8008/api/services/app/wap/WapUpload';

export default class Photos extends Component {
	constructor(props) {
		super(props);
		this.state = {
			uris: [],
			utl: '', //导入的图片路径
			imageInput: {}, //上传参数
			url1: '', //上传返回的图片路径
			thumbs: ''
		};
	}

	getPhotos = () => {
		RNCameraRoll.getAssets({ assetType: 'image', limit: 1000 })
			.then(async (response) => {
				let newPaths = [];
				console.log(response);
				let imgs = response.assets.filter((item) => item.filename != null && item.type == 'image');
				console.log(imgs);
				let uril = imgs[0].uri;
				this.setState({
					uris: imgs,
					url: uril,
					imageInput: imgs[0]
				});
				// let i = 0;
				// let timer = setInterval(()=>{
				// 	this.setState({
				// 		url:imgs[i].uri
				// 	});
				// 	i++;
				// 	if(i>=imgs.length){
				// 		clearInterval(timer);
				// 	}
				// },200)
				let i = 0;
				await imgs.map((items, index) => {
					ImageResizer.createResizedImage(items.uri, 800, 600, 'JPEG', 40)
						.then(({ uri }) => {
							i++;
							newPaths.push(uri);
							console.log(i);
							if (i >= imgs.length) {
								console.log(newPaths);
								this.setState({
									thumbs: uri
								});
							}
						})
						.catch((err) => {
							i++;
							console.log(err);
							return console.log(
								'Unable to resize the photo',
								'Check the console for full the error message'
							);
						});
				});
			})
			.catch((err) => console.error(err));
	};

	renderImages = ({ item }) => {
		const { uri, timestamp } = item;
		return (
			<Image
				source={{ uri }}
				style={{ width: width / 3, height: width / 3, borderColor: '#F00', borderWidth: 1 }}
				key={timestamp}
			/>
		);
	};

	upPhotos = () => {
		let { imageInput, thumbs } = this.state;
		const { uri, filename } = imageInput;

		let formData = new FormData();
		formData.append('width', imageInput.width);
		formData.append('height', imageInput.height);
		formData.append('file', { uri: thumbs, type: 'application/octet-stream', name: filename });

		console.log(formData);

		fetch(upurl, {
			method: 'POST',
			headers: {
				'Content-Type': 'multipart/form-data'
			},
			body: formData
		})
			.then((response) => {
				console.log(response);
				if (response.status >= 200 && response.status < 300) {
					return response.json();
				} else {
					throw response;
				}
			})
			.then((res) => {
				console.log(res);
				let url = res.result.url;
				this.setState({
					url1: url
				});
			});
	};

	render() {
		const { uris = [], url, url1, thumbs } = this.state;
		console.log(url, url1, thumbs);
		return (
			<View style={styles.container}>
				<StatusBar animated hidden />
				<TouchableOpacity onPress={this.getPhotos} style={styles.btn}>
					<Text>从本地相册导入图片</Text>
				</TouchableOpacity>
				<Image source={{ uri: url }} style={{ width: 60, height: 60, borderColor: '#F00', borderWidth: 1 }} />
				<TouchableOpacity onPress={this.upPhotos} style={styles.btn}>
					<Text>上传</Text>
				</TouchableOpacity>
				<Image
					source={{ uri: `http://192.168.31.28:8008/${url1}` }}
					style={{ width: 60, height: 60, borderColor: '#F00', borderWidth: 1 }}
				/>
			</View>
		);
	}
}
/*
{uris.length > 0 ? (
					<FlatList numColumns={3} data={uris} style={{ flex: 1 }} renderItem={this.renderImages} />
				) : (
					undefined
				)}
				<Image
					source={{ uri: url }}
					style={{ width: 60, height: 60, borderColor: '#F00', borderWidth: 1 }}
				/>
*/

const styles = StyleSheet.create({
	container: {
		flex: 1,
		justifyContent: 'center',
		alignItems: 'center'
	},
	btn: {
		padding: 10
	}
});
